/**
 * This file is part of iSecurePasswords.
 *
 * iSecurePasswords is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 *
 * iSecurePasswords is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * iSecurePasswords. If not, see <http://www.gnu.org/licenses/>.
 *
 * Author: Matthew MacGregor Created: 2012 iSecurePasswords, copyright 2013
 * Sudolink, LLC
 *
 */
package com.sudolink.io;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sudolink.crypto.CryptoException;
import com.sudolink.cryptodata.CryptInfoBundle;
import com.sudolink.cryptodata.ISecureData;
import com.sudolink.cryptodata.SecureData;
import com.sudolink.cryptodata.SecureDataManager;
import com.sudolink.isp.app.Application;
import java.io.File;
import java.io.IOException;

/**
 *
 * @author matsu
 */
public class JsonExportImport {

    private final File path;

    public JsonExportImport(String path) {
        this.path = new File(path);
    }

    public JsonExportImport(File path) {
        this.path = path;
    }

    /**
     * Imports password nodes into the system from a properly-formatted JSON
     * file. This method provides a universal import mechanism. 
     * @param isOverwritten If true, all passwords will be destroyed and replaced
     * by the import.
     * @throws IOException
     * @throws CryptoException
     */
    public void importFromJson(boolean isOverwritten) throws IOException, CryptoException {

        SecureDataManager mgr = Application.getSecureDataManager();
        CryptInfoBundle bundle = Application.getPrivateKeys();
        Fetch f = new Fetch(path);
        String data = f.fetch();
        SecureData[] nodes = new Gson().fromJson(data, SecureData[].class);
        
        if (isOverwritten) {
            mgr.resetAll(nodes);
        } else {
            mgr.addAll(nodes);
        }
        mgr.encryptEach(bundle);
        mgr.saveAll(new Store(Application.getPathToDatabase()), bundle);

    }

    public void exportToJson(boolean overwrite) throws IOException {

        SecureDataManager mgr = Application.getSecureDataManager();
        CryptInfoBundle bundle = Application.getPrivateKeys();
        mgr.decryptEach(bundle);
        ISecureData[] nodes = mgr.getAll();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(nodes);
        mgr.encryptEach(bundle);
        Store store = new Store(path);
        store.shouldOverwrite(overwrite);
        store.store(json);

    }
}
